package pl.softech.server.http;

import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import pl.softech.logger.MyLogger;
import pl.softech.server.IRequest;
import pl.softech.server.IRequestHandler;
import pl.softech.server.IRequestProcessor;
import pl.softech.server.IResponse;

public class HttpRequestProcessor implements IRequestProcessor {

    protected Logger logger = MyLogger.getLogger(getClass());
    
    private final List<IRequestHandler> handlers;

    public HttpRequestProcessor() {
        handlers = new LinkedList<IRequestHandler>();
        initHandlers();
    }

    private void initHandlers() {
        handlers.add(new HttpStaticContent());
    }

    public IResponse processRequest(IRequest request) {

        HttpResponse httpResponse = new HttpResponse();
       
        try {
            HttpRequest httpRequest = new HttpRequest(request);
            logger.logp(Level.FINEST, HttpRequestProcessor.class.getName(), "processRequest", "Request:\n" + new String(httpRequest.getRawData(), Charset.defaultCharset()));
            for (IRequestHandler h : handlers) {
                if (h.match(httpRequest)) {
                    h.handle(httpRequest, httpResponse);
                    break;
                }
            }
            
            return httpResponse.build();
            
        } catch (Exception e) {
            e.printStackTrace();
            return HttpStatus.HTTP_504.response;
            
        }
    }

}
